package com.qsd.doc4jsimpple.util;

import cn.hutool.core.collection.CollectionUtil;
import com.vladsch.flexmark.html2md.converter.FlexmarkHtmlConverter;
import com.vladsch.flexmark.util.data.MutableDataSet;
import org.apache.commons.lang3.StringUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Attribute;
import org.jsoup.nodes.Attributes;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * * @Author xujunxia
 * * @Date 2024-10-31 12:51
 * * @Description TODO
 * * wb-0455@dtdream.com
 **/
public class RichTextHelper {


    private static final Map<String, String> contentTypeToExtensionMap = new HashMap<>();

    static {
        // 常见的contentType与后缀名映射
        contentTypeToExtensionMap.put("image/jpeg", ".jpg");
        contentTypeToExtensionMap.put("image/png", ".png");
        contentTypeToExtensionMap.put("image/gif", ".gif");
        contentTypeToExtensionMap.put("application/pdf", ".pdf");
        contentTypeToExtensionMap.put("text/plain", ".txt");
        contentTypeToExtensionMap.put("application/msword", ".doc");
        contentTypeToExtensionMap.put("application/vnd.openxmlformats-officedocument.wordprocessingml.document", ".docx");
        contentTypeToExtensionMap.put("application/vnd.ms-excel", ".xls");
        contentTypeToExtensionMap.put("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", ".xlsx");
    }

    /**
     * 将html转化成markdown格式的字符串
     * @param html
     * @return
     */
    public static String convert2md(String html) {
        MutableDataSet options = new MutableDataSet();
        FlexmarkHtmlConverter converter = FlexmarkHtmlConverter.builder(options).build();
        return converter.convert(html);
    }

    public static String removeTags(String html, List<String> tags) {
        String returnStr = "";
        try {
            Document doc = Jsoup.parse(html);
            for(String tag:tags){
                Elements nodes = doc.body().select(tag);
                for (Element node : nodes) {
                    node.remove();
                }
            }

            returnStr = doc.html();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return returnStr;
    }

    public static List<Map<String,Object>> selectTags(String html, List<String> tags) {

        List<Map<String,Object>> tagNodeList = new ArrayList<Map<String,Object>>();
        try {
            Document doc = Jsoup.parse(html);
            for(String tag:tags){
                Elements nodes = doc.select(tag);
                for (Element node : nodes) {
                    Map<String,Object> tagNodeAttrbutes = new HashMap<String, Object>();
                    Attributes attributes =  node.attributes();
                    if(CollectionUtil.isNotEmpty(attributes)){
                        for (Attribute attribute : attributes) {
                            tagNodeAttrbutes.put(attribute.getKey().toLowerCase(), attribute.getValue());
                        }
                    }
                    if(CollectionUtil.isNotEmpty(tagNodeAttrbutes)){
                        tagNodeList.add(tagNodeAttrbutes);
                    }
                }
            }


        } catch (Exception e) {
            e.printStackTrace();
        }
        return tagNodeList;
    }



    public static String getImgSrc(String html) {
        String imgSrc = "";
        try {
            // 使用Jsoup解析HTML字符串，这里可以替换为从文件或网络获取HTML内容
            Document document = Jsoup.parse(html);
            // 通过标签选择器选择img标签
            Elements imgElements = document.select("img");
            for (Element imgElement : imgElements) {
                // 获取src属性的值
                imgSrc = imgElement.attr("src");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return imgSrc;
    }

    public static String replaceHttps2Http(String httpsUrl){
        String endpoint  = "http://192.168.110.40:9000/";
        String bucketName = "smartreport";
        String prefix = "/filecenter/file";
        int index = httpsUrl.indexOf(prefix);

        return endpoint + bucketName + httpsUrl.substring(index+prefix.length());
    }


    public static byte[] fetchFileFromServer(String fileUrl) {
        if(fileUrl.contains("https")){
            fileUrl = replaceHttps2Http(fileUrl);
        }
        if(StringUtils.isEmpty(fileUrl)){
            return null;
        }
        URL url = null;
        try {
            url = new URL(fileUrl);
        } catch (Exception e) {
           e.printStackTrace();
        }
        try (InputStream in = new BufferedInputStream(url.openStream());
             ByteArrayOutputStream out = new ByteArrayOutputStream()) {
            byte[] buffer = new byte[1024];
            int n;
            while ((n = in.read(buffer))!= -1) {
                out.write(buffer, 0, n);
            }
            return out.toByteArray();
        }catch(Exception e){
            e.printStackTrace();
        }
        return null;
    }


    public static String getExtensionByContentType(String contentType) {
        return contentTypeToExtensionMap.getOrDefault(contentType, "");
    }

    public static String getContentTypeByExtension(String extension) {
        for(String contentType:contentTypeToExtensionMap.keySet()){
            if(contentTypeToExtensionMap.get(contentType).contains(extension)){
                return contentType;
            }
        }
        return null;
    }

    public static String getFileExtension(String fileName) {
        int lastIndex = fileName.lastIndexOf('.');
        if (lastIndex > 0 && lastIndex < fileName.length() - 1) {
            String suffix = fileName.substring(lastIndex + 1);
         return suffix;
        }
        return null;
    }


    public static Map<String,Object> getWidthAndHeight(String urlStr ,String endpoint,String bucketName) {
        Map<String,Object> result = new HashMap<>();
        try {
            if(urlStr.indexOf("https")>-1){
                int lastIndex = urlStr.lastIndexOf('/');
                String obj = urlStr.substring(lastIndex+1);
                urlStr = endpoint + bucketName + "/" +obj;
            }

            // 网络图片的URL
            URL url = new URL(urlStr);
            // 打开网络连接并获取输入流
            InputStream inputStream = url.openStream();
            // 将输入流中的数据转换为BufferedImage对象
            BufferedImage bufferedImage = ImageIO.read(inputStream);
            int width = bufferedImage.getWidth();
            int height = bufferedImage.getHeight();
            result.put("width", width);
            result.put("height", height);
            // 关闭输入流
            inputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return result;
    }
}
